package com.lottery.system.common.utils;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author: xiaoxie
 * create: 2024-09-02 10:14
 * @BelongsPackage: com.lottery.system.common.utils
 * description: js序列化和反序列化
 */
public class JacksonUtil {
    /**
     * @description:单例模式
     * @author: xiaoxie
     * @date: 2024/9/2 10:22
     **/
    private final static ObjectMapper OBJECT_MAPPER;

    private JacksonUtil() {
    }

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }
    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * @description: js解析
     * @author: xiaoxie
     * @date: 2024/9/2 10:40
     * @param: [parser, check]
     * @return: T
     **/
    private static <T> T tryParse(Callable<T> parser,Class<? extends Exception> check ) {
        try {
            return parser.call();
        }catch (Exception var4) {
            if(check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
            throw new IllegalStateException(var4);
        }
    }
    /**
     * @description:  进一步封装js解析
     * @author: xiaoxie
     * @date: 2024/9/2 10:42
     * @param: [parser]
     * @return: T
     **/

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);
    }
    /**
     * @description: 序列化方法
     * @author: xiaoxie
     * @date: 2024/9/2 11:44
     * @param: [value]
     * @return: java.lang.String
     **/
    public static String writeValueAsString(Object value) {
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(value);
        });
    }
    /**
     * @description: 反序列化方法
     * @author: xiaoxie
     * @date: 2024/9/2 11:45
     * @param: [value, valueType]
     * @return: T
     **/
    public static <T> T readValue(String value, Class<T> valueType) {
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(value, valueType);
        });
    }

    /**
     * @description: 反序列化List
     * @author: xiaoxie
     * @date: 2024/9/2 11:50
     * @param: [value, paramType]
     * @return: T
     **/
    public static <T> T readListValue(String value, Class<?> paramType) {
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class, paramType);
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(value, javaType);
        });
    }
}

